package net.borderwars.convert;

import org.apache.bcel.generic.ClassGen;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author Eric
 *         Date: Mar 5, 2005
 *         Time: 4:30:55 PM
 */
public class CRobot {
// ------------------------------ FIELDS ------------------------------

    LinkedList<CRobotMethod> methods = new LinkedList<CRobotMethod> ();
    BufferedReader br = null;
    ArrayList<String> linesBeforeFunction = null;

    String name = null;

// --------------------------- CONSTRUCTORS ---------------------------

    public CRobot (BufferedReader br) throws IOException {
        this.br = br;
        String line = advanceUntil ("Function:");
        if (line != null) {
            String name = line.substring (line.indexOf (":") + 1);
            do {
                CRobotMethod method = new CRobotMethod (br, name);
                // System.out.println("MethodNAme " + method.name);
                method.calcArgCount (linesBeforeFunction);
                line = advanceUntil ("Function:");

                if (line != null) {
                    name = line.substring (line.indexOf (":") + 1);
                }
                methods.add (method);
            }
            while (line != null);
        }
    }

    private String advanceUntil (String lookFor) throws IOException {
        String line = null;
        linesBeforeFunction = new ArrayList<String> ();
        do {
            line = br.readLine ();
            linesBeforeFunction.add (line);
        }
        while (line.indexOf (lookFor) == -1 && line.indexOf ("Code utilization:") == -1);

        if (line.indexOf ("Code utilization:") != -1) {
            return (null);
        }

        return (line);
    }

// --------------------- GETTER / SETTER METHODS ---------------------

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

// ------------------------ CANONICAL METHODS ------------------------

    public String toString () {
        String rtn = new String ();
        for (CRobotMethod m : methods) {
            rtn = rtn + m + "\n";
        }
        return (rtn);
    }

// -------------------------- OTHER METHODS --------------------------

    public byte[] makeJavaClass (String origFile) throws IOException {
        String ints[] = new String[0];

        ClassGen cg = new ClassGen (name, "net.borderwars.robots.Robot", name + ".class", 0, ints);
        for (CRobotMethod m : methods) {
            m.addMethod (cg, origFile, name);
        }

        return (cg.getJavaClass ().getBytes ());
    }
}

